#!/usr/bin/env bash
#! Encoding UTF-8
PATH=$PATH:/bin:/sbin:/usr/bin:/usr/sbin:/usr/local/bin:/usr/local/sbin:~/bin
export PATH
set -e

BIN_FILENAME=namod
GITHUB_URL=https://github.com/hashicorp/${BIN_FILENAME}/releases
HASHICORP_CHECK_API=https://checkpoint-api.hashicorp.com/v1/check/${BIN_FILENAME}

DOWNLOADER=
if [[ -z "${DOWNLOAD_BASE_PATH}" ]] ; then
    LOCAL_PATH=$(dirname $0)
    TMP_ROOT=${LOCAL_PATH}/tmp
else
    LOCAL_PATH=${DOWNLOAD_BASE_PATH}/hashicorp/${BIN_FILENAME}
    mkdir -p ${LOCAL_PATH}
    TMP_ROOT=${DOWNLOAD_BASE_PATH}/tmp
fi

info(){
    echo "$(date +'%F %T') [INFO] " "$@"
}
waring(){
    echo "$(date +'%F %T') [WARING] " "$@"
}
fatal(){
    echo "$(date +'%F %T') [ERROR] " "$@"
    exit 1
}

# --- create tempory directory and cleanup when done ---
setup_tmp() {
    TMP_DIR=$(mktemp -p ${TMP_ROOT} -d -t exporter-install.XXXXXXXXXX)
    cleanup() {
        code=$?
        set +e
        trap - EXIT
        rm -rf ${TMP_DIR}
        exit $code
    }
    trap cleanup INT EXIT
}

get_release_version() {
  info "$0 Finding latest release"
  case $DOWNLOADER in
      curl)
          if [[ -n ${PROXY_URL} ]] ; then
              VERSION_PROGRAM=$(curl -x ${PROXY_URL} -L -s -S ${HASHICORP_CHECK_API} |awk -F',' '{for (i=1;i<=NF;i++){n=split($i,a,":"); if (a[1]=="\"current_version\"")print a[2]}}' |sed -e 's/"//g')
          else
              VERSION_PROGRAM=$(curl -L -s -S ${HASHICORP_CHECK_API} |awk -F',' '{for (i=1;i<=NF;i++){n=split($i,a,":"); if (a[1]=="\"current_version\"")print a[2]}}' |sed -e 's/"//g')
          fi
          
          ;;
      *)
          fatal "Incorrect downloader executable '$DOWNLOADER'"
          ;;
  esac
}

verify_downloader() {
    # Return failure if it doesn't exist or is no executable
    [ -x "$(which $1)" ] || return 1

    # Set verified executable as our downloader program and return success
    DOWNLOADER=$1
    return 0
}
# --- download from github url ---
download() {
    [ $# -eq 2 ] || fatal 'download needs exactly 2 arguments'

    case $DOWNLOADER in
        curl)
            if [[ -n ${PROXY_URL} ]] ; then
                curl -x ${PROXY_URL} -o $1 -sfL $2
            else
                curl -o $1 -sfL $2
            fi
            ;;
        *)
            fatal "Incorrect executable '$DOWNLOADER'"
            ;;
    esac

    # Abort if download command failed
    [ $? -eq 0 ] || waring 'Download failed'
}

main(){
    # openresty 下载
    verify_downloader curl \
        || fatal 'Can not find curl or wget for downloading files'
    setup_tmp

    get_release_version
    info "${BIN_FILENAME} release version is ${VERSION_PROGRAM}"
    mkdir -p ${LOCAL_PATH}
    HASH_URL=https://releases.hashicorp.com/${BIN_FILENAME}/${VERSION_PROGRAM#*v}/${BIN_FILENAME}_${VERSION_PROGRAM#*v}_SHA256SUMS
    download ${TMP_DIR}/sha256sums ${HASH_URL}

    for OS_VERSION in "arm64" "amd64" "armelv5" "armhfv6"; do
        TAR_PACKET=${BIN_FILENAME}_${VERSION_PROGRAM#*v}_linux_${OS_VERSION}
        if [[ -f ${LOCAL_PATH}/${TAR_PACKET}.zip ]] ; then
            waring "Promgram \"${TAR_PACKET}.zip\" already exists ."
            continue
        fi

        DOWNLOAD_URL=https://releases.hashicorp.com/${BIN_FILENAME}/${VERSION_PROGRAM#*v}/${TAR_PACKET}.zip
        download ${TMP_DIR}/${TAR_PACKET}.zip ${DOWNLOAD_URL}

        HASH_INSTALLED=$(sha256sum ${TMP_DIR}/${TAR_PACKET}.zip | awk '{print $1}')
        HASH_EXPECTED=$(grep " ${TAR_PACKET}.zip$" ${TMP_DIR}/sha256sums | awk '{print $1}')
        if [ "${HASH_EXPECTED}" != "${HASH_INSTALLED}" ]; then
            waring "Download sha256 does not match ${HASH_EXPECTED}, got ${HASH_BIN}"
        else
            info "Promgram \"${TAR_PACKET}.zip\" download success ."
            cp -f ${TMP_DIR}/${TAR_PACKET}.zip ${LOCAL_PATH}/
        fi
    done
}

main
